const mongoose = require("../db");
const Schema = mongoose.Schema;

const leadSchema = new Schema({
  leadId: { type: String, unique: true, required: true },
  name: { type: String, required: true },
  company: { type: String },
  phone: { type: String, required: true },
  email: { type: String },
  source: { 
    type: String, 
    enum: ['网站', '电话', '推荐', '广告', '其他'], 
    default: '其他' 
  },
  status: { 
    type: String, 
    enum: ['新线索', '已联系', '有兴趣', '无兴趣', '已转化'], 
    default: '新线索' 
  },
  assignedTo: { type: mongoose.Schema.Types.ObjectId, ref: 'Admin' },
  score: { type: Number, default: 0, min: 0, max: 100 },
  createTime: { type: Date, default: Date.now },
  updateTime: { type: Date, default: Date.now }
});

// 创建索引
leadSchema.index({ leadId: 1 });
leadSchema.index({ phone: 1 });
leadSchema.index({ email: 1 });
leadSchema.index({ assignedTo: 1 });
leadSchema.index({ status: 1 });
leadSchema.index({ score: -1 });
leadSchema.index({ createTime: -1 });

// 更新时间中间件
leadSchema.pre('save', function(next) {
  this.updateTime = new Date();
  next();
});

leadSchema.pre('findOneAndUpdate', function(next) {
  this.set({ updateTime: new Date() });
  next();
});

module.exports = mongoose.model("Lead", leadSchema);